import { message, Button, Select, Popconfirm, FormInstance } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { 
  getCategoryList, 
  doCreateCategory, 
  deleteCategory, 
  deleteCategoryBatch,
  updateCategory 
} from '@/services/stock-goods/api';
import CategoryDetail from './Detail';
import OptForm from './OptForm';
import { OptType } from '@/utils/constants';
import { MsgType, showMsg } from '@/utils/utils';
import PermissionControl from '@/components/PermissionControl';
import BreadcrumbDept from '@/components/BreadcrumbDept';

const CategoryList: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<STOCKGOODSAPI.CategoryItem>({})
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [optType, setOptType] = useState<string>(OptType.ADD);
  const [ids, setIds] = useState<string[]>([]);
  const [searchFlag, setSearchFlag] = useState<number>(0);
  const [clickRow, setClickRow] = useState(''); // 当前选中的行编号，用于定位颜色

  const columns: ProColumns<STOCKGOODSAPI.CategoryItem>[] = [
    {
      title: '查询范围',
      dataIndex: 'flag',
      hideInTable: true,
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        return <Select onChange={(value) => {
          setSearchFlag(value);
          if (value === 2 || value === 3) {
            formRef.current?.setFieldsValue({
              key_words: null
            })
          }
        }} allowClear>
          <Select.Option value={0}>全部</Select.Option>
          <Select.Option value={1}>指定品类</Select.Option>
          <Select.Option value={2}>仅包含商品的品类</Select.Option>
          <Select.Option value={3}>不包含商品的品类</Select.Option>
        </Select>;
      }
    },
    {
      title: '品类名称',
      dataIndex: 'key_words',
      hideInTable: true,
      hideInSearch: [2, 3].includes(searchFlag),
    },
    {
      title: '分类名称',
      dataIndex: 'class_name',
      search: false
    },
    {
      title: '检索码',
      dataIndex: 'class_py',
      search: false,
      width: 120
    },
    {
      title: '分类下商品种类',
      dataIndex: 'num',
      search: false,
      align: 'right',
      width: 120
    },
    {
      title: '操作',
      align: 'center',
      width: 120,
      valueType: 'option',
      render: (_, record) => [
        <PermissionControl key="view" action_id="200201003">
          <a onClick={() => {
            setDetailVisible(true);
            setCurrentRow(record);
          }}>查看</a>
        </PermissionControl>,

        <PermissionControl key="edit" action_id="200201004">
            <a onClick={() => {
              handleModalVisible(true);
              setCurrentRow(record);
              setOptType(OptType.EDIT);
            }}>编辑</a>
        </PermissionControl>,
          record.num === 0 && <PermissionControl key="delete" action_id="200201005">
            <Popconfirm 
              placement="topRight"
              onConfirm={async () => {
                try {
                  await deleteCategory(record.class_id as string)
                  showMsg('此分类已删除', MsgType.SUCCESS)
                  actionRef.current?.reload()
                } catch (error) {
                  showMsg(error?.data?.errmsg)
                }
              }}
              okText="确认删除"
              cancelText="再想想"
              title="您即将删除分类，是否继续？">
              <a>删除</a> 
            </Popconfirm>
          </PermissionControl>
      ]
    }
  ];

  const onRowChange = (selectedRowKeys: React.Key[], selectedRows: STOCKGOODSAPI.CategoryItem[]) => {
    if (!selectedRows.length) {
      setIds([]);
      return
    }
    const rows = selectedRows.map(item => {
      return item.class_id;
    });
    setIds(rows as string[]);
  }

  /**
   * 添加品类
   * @param fields 
   * @returns 
   */
   const handleAdd = async (fields: STOCKGOODSAPI.CategoryItem) => {
    try {
      let data = null;
      if (optType === OptType.ADD) {
        data = await doCreateCategory({ ...fields });
      } else {
        data = await updateCategory({ ...fields });
      }
      showMsg(optType === OptType.ADD ? '添加成功' : '修改成功', MsgType.SUCCESS);
      return data;
    } catch (error) {
      showMsg(error?.data?.errmsg);
      return null;
    }
  };

  return (
    <PageContainer extra={[
      <BreadcrumbDept />
     ]} breadcrumb={{}}>
      <ProTable<STOCKGOODSAPI.CategoryItem, COMMON.PageParams>
        actionRef={actionRef}
        bordered
        rowKey="class_id"
        formRef={formRef}
        search={{
          span: 6,
          optionRender: (searchConfig, formProps, dom) => {
            dom.shift();
            return [<PermissionControl key="opt" action_id="200201000">{dom}</PermissionControl>];
          }
        }}
        request={async (params) => {
          console.log(params);
          try {
            params = Object.assign({}, params, { flag: searchFlag });
            const data: STOCKGOODSAPI.CategoryItemList = await getCategoryList(params);
            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num
            };
          } catch (error) {
            message.error(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0
            };
          }
        }}
        columns={columns}
        options={false}
        rowSelection={{
          columnWidth: 80,
          onChange: onRowChange,
          getCheckboxProps: (record: STOCKGOODSAPI.CategoryItem) => ({
            disabled: record.num as number > 0
          })
        }}
        toolbar={{
          menu: {
            type: 'inline',
            items: [
              {
                key: 'add',
                label: <PermissionControl action_id="200201001">
                    <Button 
                      onClick={() => {
                        handleModalVisible(true);
                        setCurrentRow({});
                        setOptType(OptType.ADD);
                      }} 
                      icon={<PlusOutlined />} 
                      type="primary">
                        新建
                    </Button>
                  </PermissionControl>
              },
              {
                key: 'batchdelete',
                label: <PermissionControl action_id="200201002">
                    <Popconfirm 
                      disabled={!ids.length}
                      title="您即将删除选中的分类，是否继续？"
                      onConfirm={async () => {
                        try {
                          await deleteCategoryBatch(ids)
                          showMsg('此分类已删除', MsgType.SUCCESS)
                          actionRef.current?.clearSelected?.()
                          actionRef.current?.reload()
                        } catch (error) {
                          showMsg(error?.data?.errmsg)
                        }
                      }}
                      okText="确认删除"
                      cancelText="再想想">
                      <Button disabled={!ids.length} icon={<DeleteOutlined />} type="primary">
                      批量删除
                      </Button>
                    </Popconfirm>
                  </PermissionControl>
              }
            ]
          }
        }}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.class_id) }, // 点击行
            onMouseEnter: event => {}, // 鼠标移入行
            onMouseLeave: event => {},
          };
        }}
        rowClassName={(record) => {
          return record.class_id === clickRow ? 'tableRowClick' : ''
        }}
      />
      
      {
        detailVisible && <CategoryDetail 
          handleModalVisible={setDetailVisible}
          record={currentRow}
        />
      }
      
      {
        createModalVisible && <OptForm 
          handleModalVisible={handleModalVisible}
          record={currentRow}
          optType={optType}
          handleAdd={handleAdd}
          actionRef={actionRef}
        />
      }
    </PageContainer>
  );
};
export default CategoryList;
